import React, { useEffect, useState } from 'react'
import MyBreadCrumbs from './components/MyBreadCrumbs'
import { Button, Form, Input, Select, DatePicker, Dropdown, Space, Table, Tag, Drawer, Modal, Radio, message, Card, TreeSelect } from 'antd'
import { DownOutlined, ExclamationCircleFilled, SettingOutlined, EyeOutlined } from '@ant-design/icons'
import { useLocation } from 'react-router-dom'
import { getUserListApi, updateUserApi, addUserApi, getRoleApi, delUserApi, getDeptApi } from '../../apis/user'
const { confirm } = Modal;

export default function user() {
  const [sortedInfo, setSortedInfo] = useState({});
  const [filteredInfo, setFilteredInfo] = useState({});
  const [data, setData] = useState([])
  const [pagination, setPagination] = useState({
    total: 0,
    showSizechanger: true,
    showQuickJumper: true,
    showTotal: ((total) => {
      return `共${total}条`
    })
  })
  const location = useLocation()

  useEffect(() => {
    // 获取用户数据列表
    getData()
    getRoleData()
    getDeptData()
  }, [])

  const getData = React.useCallback((params) => {

    getUserListApi(params).then(res => {
      setData(res.rows)
      setPagination({
        ...pagination,
        total: res.total
      })
    })
  }, [])

  // 处理表格变换
  const handleTableChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);

    const { current, pageSize } = pagination
    getData({ pageSize, pageNum: current })

  }


  // 查询表单
  const [form] = Form.useForm();
  const { RangePicker } = DatePicker;
  const onFinish = (values) => {
    console.log(values.createtime);
  };
  const onReset = () => {
    form.resetFields();
  };

  // 下拉按钮
  const handleMenuClick = (e) => {
    console.log('click', e);
  };
  const items = [
    {
      label: '密码重置',
      key: '1',
    },
    {
      label: '导出Excel',
      key: '2',
    },

  ];
  const menuProps = {
    items,
    onClick: handleMenuClick,
  };


  // 查看
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [par, setPar] = useState({})
  function check(params) {
    setIsModalOpen(true);
    setPar(params)
  }
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

 
  let FormRef = React.useRef();
  const isMobile = true
  const [revisee, setRevisee] = useState([])//标题
  const [open, setOpen] = useState(false);
  const onClose = () => {
    setOpen(false);

  };

  // 获取所有角色数据
  const [roleData, setRoleData] = useState([])  //角色初始数据
  const getRoleData = async () => {
    const res = await getRoleApi()
    setRoleData(res.rows)
    // console.log('角色', res.rows);
  }
  // 获取所有部门数据
  const [deptMent, setDeptMent] = useState([])
  const getDeptData = async () => {
    const res = await getDeptApi()
    setDeptMent(res.rows.children)
    // console.log('部门', res.rows.children);
  }
  

  //修改或新增
  const [curUserInfo, setCurUserInfo] = useState({})//当前登录用户信息
  useEffect(()=>{
    if(open){
      if(curUserInfo){
        FormRef.current.setFieldsValue({
          ...curUserInfo,
          roleId:curUserInfo?.roleId?.split(",")
        })
      }else{
        FormRef.current.setFieldValue("password","1234qwer")
      }
    }else{
      FormRef.current?.resetFields()
    }
  },[open])
  async function onFinish1(values){
    if(curUserInfo.userId){
      // 修改
      await updateUserApi({
        ...values,
        userId:curUserInfo?.userId
      })
    }else{
      // 新增
      await addUserApi(values)
    }

    message.success(curUserInfo.userId ? "修改成功" : "新增成功")
    getData()
    setOpen(false)
  }

// 控制弹窗打开关闭
  function showDrawer(values) {
    if(values.userId){
      setRevisee('修改用户')
    }else{
      setRevisee('新增用户')
    }    
    // 弹窗打开时把用户信息存进userinfo
    setCurUserInfo(values)   
    setOpen(true);
    
  }

  

  // 表格标题
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      sorter: (a, b) => a.username.length - b.username.length,
      // sortOrder: sortedInfo.field === 'username' ? sortedInfo.order : null,
      width: '20%',
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      filterMultiple: false, //设置为单选
      filteredValue: filteredInfo.ssex || null,
      onFilter: (value, record) => record.ssex === value,
      filters: [
        { text: '男', value: '0', },
        { text: '女', value: '1' },
        { text: '保密', value: '2' },
      ],
      render(text) {
        switch (text) {
          case '0': return '男';
          case '1': return '女';
          case '2': return '保密';
        }
      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      filteredValue: filteredInfo.status || null,
      filterMultiple: false, //设置为单选
      filters: [
        { text: '锁定', value: '0', },
        { text: '有效', value: '1' },
      ],
      render(text) {
        switch (text) {
          case '0': return <Tag color='red'>锁定</Tag>;
          case '1': return <Tag color='green'>有效</Tag>;
        }
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      // sortOrder: sortedInfo.field === 'createTime' ? sortedInfo.order : null,
      width: '20%',
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          <SettingOutlined type='primary'  size='small' onClick={() => showDrawer(record)} />
          <EyeOutlined type='primary' size='small' onClick={() => check(record)} />
        </Space>
      ),
    },
  ];


  // 选中
  const [userId, setUserId] = useState()
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      
      setUserId(selectedRowKeys)
    }
  };
  //删除
  function onDelete() {
    confirm({
      title: '确定删除所选中的记录？',
      icon: <ExclamationCircleFilled />,
      content: '当你点击按钮后，这些记录将会被彻底删除',
      cancelText: '取消',
      okText: '确定',
      onOk() {
        delUserApi(userId).then(res => {
          getData()
          message.success('用户删除成功')
        })
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  }

  return (
    <div>
      <div>
        <MyBreadCrumbs pathname={location.pathname}></MyBreadCrumbs>
      </div>
      <div>
        <Form form={form} name="control-hooks" onFinish={onFinish} style={{ display: 'flex', flexWrap: 'wrap', margin: '40px 0 0 80px', }}>
          <Form.Item name="username" label="用户名" style={{ width: 650 }}>
            <Input />
          </Form.Item>
          <Form.Item label="部门" name="deptId" style={{ width: 650, margin: '0 100px' }}>
            <Select>
              <Select.Option value={1} >开发部</Select.Option>
              <Select.Option value={4} >市场部</Select.Option>
              <Select.Option value={5}>人事部</Select.Option>
              <Select.Option value={6}>测试部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="创建时间" name="createtime" style={{ margin: '0 100px 0 0' }}>
            <RangePicker style={{ width: 580 }} />
          </Form.Item>
          <Form.Item >
            <Button type="primary" htmlType="submit" style={{ margin: '0 20px 0 490px' }}>查询</Button>
            <Button htmlType="button" onClick={onReset}>重置</Button>
          </Form.Item>
        </Form>
      </div>
      <div style={{marginBottom:20}}>
        <Button onClick={showDrawer}>新增</Button>
        <Drawer
          title={revisee}
          placement="right"
          onClose={onClose}
          width={isMobile ? "50%" : "40%"}
          footer={[
            <Button key={1} onClick={onClose} style={{ marginRight: 30 }}>
              取消
            </Button>,
            <Button key={2} type="primary" onClick={()=>(FormRef.current.submit())}>
              确定
            </Button>
          ]}
          open={open}>
          <Form
            ref={FormRef}
            name="basic1"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            onFinish={onFinish1}
          >
            <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入正确的用户名' }]}>
              <Input type='text' />
            </Form.Item>
            <Form.Item label="密码" name="password">
              <Input.Password />
            </Form.Item>
            <Form.Item label="邮箱" name="email">
              <Input />
            </Form.Item>
            <Form.Item label="手机" name="mobile">
              <Input />
            </Form.Item>
            <Form.Item label="角色" name="roleId" rules={[{ required: true }]}>
              <Select               
                mode="multiple"
                placeholder='请选择角色'
                // onChange={handleTableChange}
                style={{ width: '100%' }}               
              >
                {
                  roleData.map(item =>{
                    return <Select.Option key={item.roleId} value={String(item.roleId)}>{item.roleName}</Select.Option>
                  })
                }
              </Select>
            </Form.Item>
            <Form.Item label="部门" name="deptId">
              
                <TreeSelect treeData={deptMent} />
             
            </Form.Item>
            <Form.Item label="性别" name="ssex" rules={[{ required: true }]}>
              <Radio.Group>
                <Radio value="0"> 男 </Radio>
                <Radio value="1"> 女 </Radio>
                <Radio value="2"> 保密 </Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="状态" name="status" rules={[{ required: true }]}>
              <Radio.Group>
                <Radio value="0"> 锁定 </Radio>
                <Radio value="1"> 有效 </Radio>

              </Radio.Group>
            </Form.Item>

          </Form>

        </Drawer>
        <Button style={{ margin: '0 10px' }} onClick={onDelete}>删除</Button>
        <Dropdown menu={menuProps}>
          <Button>
            <Space>
              更多操作
              <DownOutlined />
            </Space>
          </Button>
        </Dropdown>
      </div>
      <div>
        <Table
          rowSelection={rowSelection}
          rowKey="userId"
          pagination={pagination}
          onChange={handleTableChange}
          columns={columns}
          dataSource={data}
          scroll={{ x: true }}
        />
        <Modal title="用户信息"
          width={750}
          footer={null} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <div className='content'>
            <Card style={{width: 300}}>
              <img src={'http://xawn.f3322.net:8002/distremote/static/avatar/' + par.avatar} style={{ width: 110, height: 110 }} />
            </Card>
            <Card>
              <p >账户：{par.username}</p>
              <p>角色：{par.roleName}</p>
              <p>性别：{par.ssex === 0 ? "男" : "女"}</p>
              <p>电话：{par.mobile}</p>
              <p>邮箱：{par.email}</p>
            </Card>
            <Card>
              <p>部门：{par.deptName}</p>
              <p>状态：{par.status === 1 ? <Tag color='green'>有效</Tag> : <Tag color='red'>锁定</Tag>}</p>
              <p>创建时间：{par.createTime}</p>
              <p>最近登录：{par.lastLoginTime}</p>
              <p>描述：{par.description}</p>
            </Card>
          </div>

        </Modal>
      </div>
    </div>
  )
}
